package com.example.hw_3.common.interceptor;

import com.example.hw_3.common.utils.JwtUtil;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
//拦截器
public class JwtInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");

        if (token == null || !JwtUtil.validateToken(token)) {
            response.setStatus(401); // 未认证
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("无效或缺失Token");
            return false;
        }

        return true; // 放行
    }
}